package team.pwy.controller;

import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import team.pwy.GameLeaderboard;
import team.pwy.consts.RbmConsts;
import team.pwy.mapper.MovieMapper;
import team.pwy.mapper.SeatMapper;
import team.pwy.pojo.dto.OrderDTO;
import team.pwy.pojo.entity.Movie;
import team.pwy.pojo.entity.Order;
import team.pwy.service.MovieService;
import team.pwy.service.OrderService;
import team.pwy.service.SessionService;
import team.pwy.vo.Result;
import team.pwy.vo.ResultPage;

import java.util.*;

@RestController
@RequestMapping("order")
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private SessionService sessionService;

    @Resource
    private SeatMapper seatMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private MovieService movieService;

    @Resource
    private MovieMapper movieMapper;

    private Jedis jedis;

    @GetMapping
    public ResultPage findByUserId(Integer userId, Integer pageNum, Integer pageSize) {
        PageInfo<Order> orderPageInfo = orderService.findByUserId(userId, pageNum, pageSize);
        List<OrderDTO> orderDTOList = new ArrayList<>();
        for (Order order : orderPageInfo.getList()) {
            OrderDTO orderDTO = new OrderDTO();
            orderDTO.setId(order.getId());
            orderDTO.setNumber(order.getNumber());
            orderDTO.setUserId(order.getUserId());
            orderDTO.setPhone(order.getPhone());
            orderDTO.setMovieId(order.getMovieId());
            orderDTO.setMovieTitle(order.getMovieTitle());
            orderDTO.setPosterImg(order.getPosterImg());
            orderDTO.setMoviePrice(order.getMoviePrice());
            orderDTO.setQuota(order.getQuota());
            orderDTO.setTotal(order.getTotal());
            orderDTO.setStatus(order.getStatus());
            orderDTO.setCreateTime(order.getCreateTime());
            orderDTO.setCouponId(order.getCouponId());
            orderDTO.setCouponMoney(order.getCouponMoney());
            orderDTO.setStartTime(sessionService.findBySessionId(order.getSessionId()).getStarTime());
            List<Integer> seatId = seatMapper.findByOrderId(order.getId());
            orderDTO.setSeatId(seatId);
            orderDTOList.add(orderDTO);
        }

        return new ResultPage("200", "查询订单", orderDTOList, orderPageInfo.getSize(), orderPageInfo.getPages());
    }

    /**
     * @param orderDTO:
     * @return Result
     * @author DaiLing
     * @description 确认选座
     * @date 2024/1/24 14:46
     */
    @PostMapping()
    public Result addOrder(@RequestBody OrderDTO orderDTO) {
        orderDTO.setCreateTime(new Date());
        // 添加订单
        Integer orderId = orderService.addOrder(orderDTO);

        // 创建RabbitMQ任务
        rabbitTemplate.convertAndSend(RbmConsts.ORDER_ERROR, orderId);

        if (orderId != -1) {
            StringBuilder str = new StringBuilder(orderId + "&");
            List<Integer> seatList = orderDTO.getSeatId();
            for (int i = 0; i < seatList.size(); i++) {
                if (seatList.size() - 1 != i) {
                    str.append(seatList.get(i)).append(",");
                } else {
                    str.append(seatList.get(i));
                }
            }
            return new Result("200", "订单保存成工", str.toString());
        } else {
            return new Result("400", "保存订单失败");
        }
    }

    @GetMapping("{id}")
    public Result findById(@PathVariable Integer id) {
        Order order = orderService.findById(id);
        return order != null ? new Result("200", "查询订单", order) : new Result("400", "失败");
    }

    @PutMapping()
    public Result updateById(Integer id, Integer payStatus) {

        jedis = new Jedis("localhost", 6379);
        jedis.auth("roots");

        orderService.updateById(id, payStatus);

        GameLeaderboard leaderboard = new GameLeaderboard();
        Order order = orderService.findById(id);
        Movie movie = movieService.findById(order.getMovieId());
        // 刷新redis排行旁
        leaderboard.updateScore(movie.getId() + "&" + movie.getTitle() + "&" + movie.getPosterImg(), movie.getPrice() * order.getQuota());

        movieMapper.updateGrossed(order.getQuota() * order.getMoviePrice(), order.getMovieId());
        rabbitTemplate.convertAndSend(RbmConsts.ORDER_SUCCESS, order.getId());

        return new Result("200", "支付成功");
    }

    @DeleteMapping()
    public Result deleteByIdAndUerId(Integer id, Integer userId) {
        Integer count = orderService.deleteByIdAndUerId(id, userId);
        return count == 0 ? new Result("400", "删除订单失败") : new Result("200", "订单删除成功");
    }
}
